package cc.telecomdigital.tdstock.trading;

import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.Services.CommunicTools;
import cc.telecomdigital.tdstock.trading.Common.Trade_AppConstant;
import cc.telecomdigital.tdstock.trading.Services.TradeAppInfo;
import cc.telecomdigital.tdstock.trading.Services.TradeChangePassword;
import cc.telecomdigital.tdstock.trading.Services.TradeChangePassword.ITradeChangePasswordResponse;
import cc.telecomdigital.tdstock.trading.Services.TradeChangePassword.TradeChangePasswordResult;
import cc.telecomdigital.tdstock.trading.Tools.ViewCtrlHelper;
import cc.telecomdigital.tdstock.trading.widget.AppDialogOK;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.InputFilter;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

public class Trade_ChgPasswordActivity extends Trade_TemplateActivity implements
	OnClickListener
{
	@Override
	public void onCreate(Bundle iSaveInstance)
	{
		super.onCreate(iSaveInstance);
		setContentView(R.layout.changepassword);

		// Map the button function
		// Set Header as UserName
		TextView textViewObj = (TextView) findViewById(R.id.view_acctheader_Title);
		if (TradeAppInfo.IsDemoAccount())
		{
			EditText editObj;

			String tmpPassword;

			textViewObj.setText(TradeAppInfo.GetUserName());
			//tmpPassword = GetUserPassword();
			tmpPassword = "tdldemopassword";
			editObj = (EditText) findViewById(R.id.changepassword_OldPasswordEdit);
			editObj.setText(tmpPassword);
			ViewCtrlHelper.SetEnableRequestView(this,
					R.id.changepassword_OldPasswordEdit, false);
			ViewCtrlHelper.SetEnableRequestView(this,
					R.id.changepassword_OldPasswordClearBut, false);

		}
		else
			textViewObj.setText(R.string.chgPasswordText);

		findViewById(R.id.view_acctheader_Refresh).setVisibility(
				View.INVISIBLE);
		findViewById(R.id.view_acctheader_Home).setOnClickListener(this);

		findViewById(R.id.changepassword_OldPasswordClearBut)
				.setOnClickListener(this);
		findViewById(R.id.changepassword_NewPasswordClearBut)
				.setOnClickListener(this);
		findViewById(R.id.changepassword_ConfirmPasswordClearBut)
				.setOnClickListener(this);

		EditText editTextObj;
		InputFilter[] FilterArray;

		FilterArray = new InputFilter[1];
		FilterArray[0] = new InputFilter.LengthFilter(
				Trade_AppConstant.maxPasswordLength);
		editTextObj = (EditText) findViewById(R.id.changepassword_OldPasswordEdit);
		editTextObj.setOnFocusChangeListener(_keyboardPopListener);
		editTextObj.setFilters(FilterArray);

		FilterArray = new InputFilter[1];
		FilterArray[0] = new InputFilter.LengthFilter(
				Trade_AppConstant.maxPasswordLength);
		editTextObj = (EditText) findViewById(R.id.changepassword_NewPasswordEdit);
		editTextObj.setOnFocusChangeListener(_keyboardPopListener);
		editTextObj.setFilters(FilterArray);

		FilterArray = new InputFilter[1];
		FilterArray[0] = new InputFilter.LengthFilter(
				Trade_AppConstant.maxPasswordLength);
		editTextObj = (EditText) findViewById(R.id.changepassword_ConfirmPasswordEdit);
		editTextObj.setOnFocusChangeListener(_keyboardPopListener);
		editTextObj.setFilters(FilterArray);

		findViewById(R.id.changePassword_SendBut).setOnClickListener(this);

		((EditText) findViewById(R.id.changepassword_ConfirmPasswordEdit))
				.setOnEditorActionListener(new TextView.OnEditorActionListener()
				{
					@Override
					public boolean onEditorAction(TextView v,
							int actionId, KeyEvent event)
					{
						if (actionId == EditorInfo.IME_ACTION_DONE)
						{
							// Close Keyboard
							HideKeyBoard();
							findViewById(R.id.changePassword_SendBut).performClick();
							return true;
						}
						return false;
					}
				});
	}

	private boolean	firstCreate	= true;

	// Happens when first with to this View
	@Override
	public void onResume()
	{
		super.onResume();
		// Send A request to show keyboard
		if (firstCreate == true)
		{
			if (TradeAppInfo.IsDemoAccount() == false)
				ShowKeyBoard(findViewById(R.id.changepassword_OldPasswordEdit));
			else
				ShowKeyBoard(findViewById(R.id.changepassword_NewPasswordEdit));
			firstCreate = false;
		}
	}

	/*
	 * //Use super.onBackPressed();
	 * 
	 * @Override public void onBackPressed() {
	 * SwapActivity(tradingOptionActivity.class, true, SWAP_DIRECTION.BACK); }
	 */

	private void HandlePasswordChangeResult(TradeChangePasswordResult iResult)
	{
		AppDialogOK promptDialog;

		promptDialog = null;
		if ((iResult.BrokerMessage != null)
				&& (iResult.BrokerMessage.length() != 0))
		{
			promptDialog = new AppDialogOK(this);
			promptDialog.SetTextContent(iResult.BrokerMessage);
			promptDialog.SetButtonText(R.string.okText);
			// return features are based on specification
		}

		// Change Success full (3), duplicate Login (12)
		if (iResult.StatusCode.equals("3") || iResult.StatusCode.equals("12"))
		{
			// Login Session expired and kick user out to the login page
//			if (iResult.StatusCode.equals("3"))
//				SetUserPassword(newUserPassword);

			DismissWaitingDialog();
			// Back to the previous window, the trading option
			if (promptDialog != null)
			{
				promptDialog.show(new AppDialogOK.IAppDialogOK()
				{
					@Override
					public void OnDialogCancel(DialogInterface iDialog)
					{
						SetToLoginActivity();
					}

					@Override
					public void OnOK_Click(DialogInterface iDialog)
					{
						SetToLoginActivity();
					}

				}, true);
				return;
			}
			
			SetToLoginActivity();
			return;
		}

		DismissWaitingDialog();
		// Prompt Error if there are one and do not know what to do
		if (promptDialog != null)
			promptDialog.show(null, true);
	}

	@Override
	public void onClick(View iViewObj)
	{
		int objId;

		objId = iViewObj.getId();
		switch (objId)
		{
			case R.id.changePassword_SendBut:
				if (isTradeChangePasswordStart == true)
					break;
				if (ValidateAndSubmitPasswordChange() == true)
					HideKeyBoard();				
				break;
			case R.id.changepassword_ConfirmPasswordClearBut:
				((EditText) findViewById(R.id.changepassword_ConfirmPasswordEdit))
						.setText("");
				break;
			case R.id.changepassword_NewPasswordClearBut:
				((EditText) findViewById(R.id.changepassword_NewPasswordEdit))
						.setText("");
				break;
			case R.id.changepassword_OldPasswordClearBut:
				((EditText) findViewById(R.id.changepassword_OldPasswordEdit))
						.setText("");
				break;
			case R.id.view_acctheader_Home:
				HideKeyBoard();
				SwitchBackActivity();
				break;
		}
	}

	private AppDialogOK promptMessage = null;
	private void ShowPromptMessage(String iContent)
	{
		if (promptMessage != null)
			promptMessage.dismiss();
		
		DismissWaitingDialog();
		promptMessage = ShowInfoBox(iContent);
	}

	private String	newUserPassword	= null;

	private boolean isTradeChangePasswordStart = false;
	private boolean ValidateAndSubmitPasswordChange()
	{
		// Perform Validation
		EditText editBoxObj;
		String oldPass, newPass, confirmPass;

		// Make sure they are not empty
		editBoxObj = (EditText) findViewById(R.id.changepassword_OldPasswordEdit);
		oldPass = editBoxObj.getText().toString();
		if (!CommunicTools.isASCIIString(oldPass))
		{
			ShowPromptMessage(getString(R.string.passwordNoEmpty));
			return false;
		}

		editBoxObj = (EditText) findViewById(R.id.changepassword_NewPasswordEdit);
		newPass = editBoxObj.getText().toString();
		if (!CommunicTools.isASCIIString(newPass))
		{
			ShowPromptMessage(getString(R.string.passwordNoEmpty));
			return false;
		}

		if (newPass.length() >= Trade_AppConstant.maxPasswordLength)
		{
			ShowPromptMessage(getString(R.string.textExceedLimit));
			return false;
		}

		editBoxObj = (EditText) findViewById(R.id.changepassword_ConfirmPasswordEdit);
		confirmPass = editBoxObj.getText().toString();
		if (!CommunicTools.isASCIIString(confirmPass))
		{
			ShowPromptMessage(getString(R.string.passwordNoEmpty));
			// PromptEditBoxError(R.id.confirmPasswordParam);
			return false;
		}

		// Make sure the new and confirm are identical
		if (newPass.equals(confirmPass) == false)
		{
			ShowPromptMessage(getString(R.string.passwordNotMatch));
			return false;
		}

		newUserPassword = newPass;

		ShowWaitingDialog();

		if (TradeAppInfo.IsDemoAccount() == false)
		{
			if (TradeAppInfo.HasSessionTimeExpired())
			{
				ShowTimeExpiredBox();
				return false;
			}
			
			// Check Network, but password is correct
			if (IsNetworkAvailable() == false)
			{
				ShowPromptMessage(getString(R.string.commErrorText));
				return true;
			}
			
		}
		
		isTradeChangePasswordStart = true;
		final TradeChangePassword passwordRequest = new TradeChangePassword(this);
		passwordRequest.SetUserInformation(TradeAppInfo.GetUserName(), oldPass, newUserPassword);
		passwordRequest.SendRequest(TradeAppInfo.IsDemoAccount(),
				new ITradeChangePasswordResponse()
				{
					@Override
					public void ResponseFunc(boolean iSuccessfulSend,
							TradeChangePasswordResult iResponse)
					{
						isTradeChangePasswordStart = false;
						if (iSuccessfulSend == false)
						{
							ShowPromptMessage(getString(R.string.commErrorText));
							return;
						}
						HandlePasswordChangeResult(iResponse);
						passwordRequest.Dispose();
					}
				});
		return true;
	}

	private static final int	CLEAR_CONTENT	= 1;

	@Override
	public boolean onCreateOptionsMenu(Menu iMenu)
	{
		super.onCreateOptionsMenu(iMenu);
		// Add the menu Item to the menu
		MenuItem menuItemObj = iMenu.add(0, CLEAR_CONTENT, Menu.NONE,
				R.string.resetAllPasswords);
		menuItemObj.setIcon(R.drawable.ic_menu_edit);
		menuItemObj.setShortcut('0', 'c');

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem iMenu)
	{
		super.onOptionsItemSelected(iMenu);
		switch (iMenu.getItemId())
		{
			case CLEAR_CONTENT:
				if (TradeAppInfo.IsDemoAccount() == false)
					((EditText) findViewById(R.id.changepassword_OldPasswordEdit))
							.setText("");
				((EditText) findViewById(R.id.changepassword_NewPasswordEdit))
						.setText("");
				((EditText) findViewById(R.id.changepassword_ConfirmPasswordEdit))
						.setText("");
				return true;
		}
		return false;
	}
}
